import store from "../store";
import accounting from "accounting";

export { parseTime, formatTime } from "@/utils";

function pluralize(time, label) {
  if (time === 1) {
    return time + label;
  }
  return time + label + "s";
}

export const dateformat = (value) => {
  return (value && value.substr(0, 10)) || "";
};

export function timeAgo(time) {
  const between = Date.now() / 1000 - Number(time);
  if (between < 3600) {
    return pluralize(~~(between / 60), " minute");
  } else if (between < 86400) {
    return pluralize(~~(between / 3600), " hour");
  } else {
    return pluralize(~~(between / 86400), " day");
  }
}
//integer
export const toInteger = (value) => {
  return value.replace(/[^\d]/g, "");
};
export const toFixed2 = (value) => {
  let realVal = Number(value).toFixed(2);
  return Number(realVal);
};
export const toFixed3 = (value) => {
  let realVal = Number(value).toFixed(3);
  return Number(realVal);
};
export const toFixed4 = (value) => {
  let realVal = Number(value).toFixed(4);
  return Number(realVal);
};

/* 数字 格式化*/
export function numberFormatter(num, digits) {
  const si = [
    { value: 1e18, symbol: "E" },
    { value: 1e15, symbol: "P" },
    { value: 1e12, symbol: "T" },
    { value: 1e9, symbol: "G" },
    { value: 1e6, symbol: "M" },
    { value: 1e3, symbol: "k" },
  ];
  for (let i = 0; i < si.length; i++) {
    if (num >= si[i].value) {
      return (num / si[i].value + 0.1).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, "$1") + si[i].symbol;
    }
  }
  return num.toString();
}

export function toThousandslsFilter(num) {
  return (+num || 0).toString().replace(/^-?\d+/g, (m) => m.replace(/(?=(?!\b)(\d{3})+$)/g, ","));
}

export const unformat = (value = "0.00") => {
  return accounting.unformat(value);
};
export const formatMoney = (value = "0.00") => {
  return accounting.formatMoney(value);
};
export const formatInter = (value = "0.00") => {
  return accounting.formatNumber(value, 0, ",", ".");
};
export const formatNumber2 = (value = "0.00") => {
  return accounting.formatNumber(value, 2, ",", ".");
};
export const formatNumber6 = (value = "0.00") => {
  return accounting.formatNumber(value, 6, ",", ".");
};
export const formatNumber4 = (value = "0.00") => {
  const weight_format = store.getters.weight_format;
  return accounting.formatNumber(value, weight_format, ",", ".");
};
